package com.ycfmedical.bed.present;

import android.graphics.Color;
import android.os.StrictMode;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.ycfmedical.bed.local.DataManager;
import com.ycfmedical.bed.model.ChartManage;
import com.ycfmedical.bed.serverdata.DBUtil;
import com.ycfmedical.bed.ui.fragment.VsHistoryFragment;
import com.ycfmedical.bed.utils.ConvertOrderCheckoutUtil;
import com.ycfmedical.bed.utils.CountTime;
import com.ycfmedical.bed.utils.MyXFormatter;
import com.ycfmedical.bed.utils.SleepCount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017-04-13.
 */

public class VsHistoryPresenter extends XPresent<VsHistoryFragment> {
    private ArrayList<Entry> entrys;
    private ChartManage chartManage;
    private DBUtil dbutil;

    public void initPresenter() {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        dbutil = DBUtil.getInstance();
        chartManage = getV().getChartManage();
    }

    public void ask(String time, String name,String userId) {
        entrys = getV().getEntrys();
        switch (name) {
            case "心率":
                askdata(time, name,userId);
                getV().getShow_type().setText("次/min");
                break;
            case "呼吸":
                askdata(time, name,userId);
                getV().getShow_type().setText("次/min");
                break;
            case "温度":
                askTemperature(time, name,userId);
                getV().getShow_type().setText("\u2103");
                break;
            case "睡眠":
                askdata(time, "睡眠",userId);
                break;
            default:
                break;
        }
    }
        /**
         * 请求体温历史数据
         * */
    private void askTemperature(String time, String name,String userId) {
        entrys.clear();
        List<HashMap<String, String>> list = dbutil.get_temp_data(time, userId);
        int average = 0;
        if (list.size() == 0) {

            Toast.makeText(getV().getContext(), "没有数据", Toast.LENGTH_SHORT).show();
            getV().getText_average().setText("0");
        } else {
            for (int i = 0; i < list.size(); i++) {
                int num = Integer.parseInt(list.get(i).get(name).replace(" ", ""));
                average += num;
                entrys.add(new Entry(entrys.size(), num));
                num = 0;
            }
            getV().getText_average().setText(average / list.size() + "");
            refurbish(chartManage,entrys,name);
        }
    }

    private void askdata(String time, String name,String userId) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                List<HashMap<String, String>> list = dbutil.get_data(time,userId);
                if (list != null) {
                    rx.Observable.create(new rx.Observable.OnSubscribe<List>() {
                        @Override
                        public void call(Subscriber<? super List> subscriber) {
                            subscriber.onNext(list);
                        }
                    }).onBackpressureDrop()
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeOn(Schedulers.immediate())
                            .subscribe(new Subscriber<List>() {
                                @Override
                                public void onCompleted() {
                                    //先判断再解除绑定
                                    if (isUnsubscribed()) {
                                        unsubscribe();
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    XLog.e("SJH", e.toString());
                                }

                                @Override
                                public void onNext(List list) {
                                    resolve(list, name);
                                    request(1);
                                }
                            });
                } else {
                    Toast.makeText(getV().getContext(), "没有数据", Toast.LENGTH_SHORT).show();
                }
            }
        }.start();
    }

    private void resolve(List<HashMap<String, String>> list, String name) {
        entrys.clear();
        int average = 0;
        if (list.size() == 0) {

            Toast.makeText(getV().getContext(), "没有数据", Toast.LENGTH_SHORT).show();
            getV().getText_average().setText("0");
        } else {
            if (name.equals("睡眠")) {
                askSleep(list);
            } else {
                for (int i = 0; i < list.size(); i++) {
                    int num = ConvertOrderCheckoutUtil.StrC16T10(list.get(i).get(name).replace(" ", ""));
                    average += num;
                    entrys.add(new Entry(entrys.size(), num));
                    num = 0;
                }
                getV().getText_average().setText(average / list.size() + "");
                //设置X轴标签
                setXLabelText(list,name);
            }
        }
        showSleepStatus(SleepCount.sleepStatus(entrys));

        refurbish( chartManage,entrys,name);
    }

    private void setXLabelText(List<HashMap<String, String>> list, String name) {
        int XCont = 0;
        String[] XText = new String[list.size()];
            if(name.equals("睡眠")){ return; }

            for(int i = 0;i<list.size();i++){
                XText[XCont] = list.get(i).get("时间").substring(10,16);
                XCont++;
            }
        ChartManage.setXText(getV().getChartManage().getLineCharts().get(0),10,new MyXFormatter(XText));
    }

    /**
         * 将数据更新到图表
         * */
    private void refurbish(ChartManage chartManage, ArrayList<Entry> entrys,String type) {
        switch (type){
            case "睡眠":
                chartManage.setLineData(0, entrys, true);
                chartManage.setLine(0, Color.rgb(17, 116, 228), false, LineDataSet.Mode.CUBIC_BEZIER);
                break;
            case "心率":
                chartManage.setLineData(0, entrys, false);
                chartManage.setLine(0, Color.rgb(47, 201, 27), false, LineDataSet.Mode.CUBIC_BEZIER);
                break;
            case "呼吸":
                chartManage.setLineData(0, entrys, false);
                chartManage.setLine(0, Color.rgb(27, 88, 201), false, LineDataSet.Mode.CUBIC_BEZIER);
                break;
            case "温度":
                chartManage.setLineData(0, entrys, false);
                chartManage.setLine(0, Color.rgb(209, 74, 25), false, LineDataSet.Mode.CUBIC_BEZIER);
                break;
            default: break;
        }

        chartManage.getLineCharts().get(0).getXAxis().setAxisMaximum(entrys.size());
        chartManage.getLineCharts().get(0).notifyDataSetChanged();
        chartManage.getLineCharts().get(0).invalidate();
    }

    private void showSleepStatus(Integer[] sleepStatus) {
        if(sleepStatus[0] == null){
            return;
        }
        HashMap<String, TextView> texts = getV().getTexts();
        texts.get("深睡").setText("深睡:" + sleepStatus[0] + "%");
        texts.get("中睡").setText("中睡:" + sleepStatus[1] + "%");
        texts.get("浅睡").setText("浅睡:" + sleepStatus[2] + "%");
        texts.get("清醒").setText("清醒:" + sleepStatus[3] + "%");
    }

    /**
     * 睡眠数据要单独算
     */
    private void askSleep(List<HashMap<String, String>> list) {
        String [] Xtext = new String[list.size()/10+10];
        int num = 1;
        int data = 0;
        int Xindex = 0;
        for (int i = 0; i < list.size(); i++) {
            if (ConvertOrderCheckoutUtil.StrC16T10(list.get(i).get("心率")) == 0) {
                continue;
            }
            num++;
            if (list.get(i).get("体动").equals("4F")) {
                data += 40;
            }
            data += ConvertOrderCheckoutUtil.StrC16T10(list.get(i).get("心率").replace(" ", ""));
            data += ConvertOrderCheckoutUtil.StrC16T10(list.get(i).get("呼吸").replace(" ", ""));
            if (num == 10 || i == list.size()) {
                 Xtext[Xindex] = list.get(i).get("时间").substring(10,16);
                entrys.add(new Entry(entrys.size(), data / num));
                data = 0;
                num = 1;
                Xindex++;
            }
        }
        ChartManage.setXText(getV().getChartManage().getLineCharts().get(0),10,new MyXFormatter(Xtext));
        getV().getText_average().setText(CountTime.count(countSleep(list), countRise(list)));
    }

    /**
     * 计算开始睡觉时间
     */
    private String countSleep(List<HashMap<String, String>> list) {
        String StartTime = "";
        for (int sleep = 0; sleep < entrys.size(); sleep++) {
            if (entrys.get(0).getY() - 5 > entrys.get(sleep).getY()) {
                StartTime = list.get(sleep * 10).get("时间");
                break;
            }
        }
        return StartTime;
    }

    /**
     * 计算结束睡觉时间
     */
    private String countRise(List<HashMap<String, String>> list) {
        String entTime = "";
        for (int rise = 0; rise < entrys.size(); rise++) {
            if (entrys.get(entrys.size() - 1).getY() - 5 > entrys.get(entrys.size() - (rise + 1)).getY()) {
                entTime = list.get((list.size() - rise * 10)).get("时间");
                break;
            }
        }
        return entTime;
    }
}
